<?php

namespace control;
/*
*项目核算明细账类
*/

class projectDetailsClass extends adIndexClass
{
    private const page       = 'projectDetails';
    private const title      = '项目核算明细账';
    public const  typeOption = ['client' => '客户', 'supplier' => '供应商', 'staff' => '员工', 'department' => '部门', 'project' => '项目', 'material' => '存货', 'cash' => '现金流'];
    public static bool $isFormat = false;//是否格式化数字

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        //生成查询表单
        switch ($workFlow) {
            case '客户':
                $kehu = query('kehu', "coid = '" . self::$coid . "' order by time asc");
                $option = [
                    '客户' => clientProfileClass::kehuSelect(array(
                        'name' => 'targetId',
                        'fun' => 'getClientNameAndCode',
                        'value' => $kehu['khid'],
                        'valueText' => clientProfileClass::getName($kehu['khid'], false, ' ')
                    ))
                ];
                break;
            case '供应商':
                $supplier = query('supplier', "coid = '" . self::$coid . "'  order by time asc");
                $option = [
                    '供应商' => supplierClass::supplierSelect([
                        'name' => 'targetId',
                        'fun' => 'getSupplier',
                        'value' => $supplier['id'],
                        'valueText' => supplierClass::getName($supplier['id'], false, ' ')
                    ])
                ];
                break;
            case '员工':
                $staff = query('staff', "state !='离职'  order by time asc");
                $option = [
                    '员工' => selectMultiple(array(
                        'name' => 'targetId',
                        'value' => $staff['stid'],
                        'table' => 'staff',
                        'where' => "1=1 order by orderNo asc",
                        'sqlId' => 'stid',
                        'sqlField' => 'name',
                        'class' => 'width200'
                    ))
                ];
                break;
            case '部门':
                $department = query('department', "1=1 order by time asc");
                $option = [
                    '部门' => selectMultiple(array(
                        'name' => 'targetId',
                        'value' => $department['id'],
                        'field' => "concat(orderNo,name) as name,id",
                        'table' => 'department',
                        'where' => "1=1 order by orderNo asc",
                        'sqlId' => 'id',
                        'sqlField' => 'name',
                        'class' => 'width200'
                    ))
                ];
                break;
            case '存货':
                $material    = query('material', "coid='" . self::$coid . "' and state = '启用' order by time asc");
                $option = [
                    '存货名称' => text(array('name' => 'materialName', 'value' => materialClass::getName($material['id'], ''), 'id' => 'materialId')) .
                        hidden(array('name' => 'targetId', 'value' => $material['id'])) . <<<eof
<script>
$("#materialId").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=voucherEdit&fun=getMaterial',
    callback:function(data,e){
       e.siblings("input[name='targetId']").val(data.id)
}}) 
</script>
eof
                ];
                break;
            case '现金流':
                $cash = query('cash', "coid = '" . self::$coid . "' order by code asc");
                $option = [
                    '现金流' => selectMultiple(array(
                        'name' => 'targetId',
                        'field' => "concat(code,name) as name,id", 'value' => $cash['id'],
                        'table' => 'cash',
                        'where' => "coid='" . self::$coid . "' order by code asc",
                        'sqlId' => 'id',
                        'sqlField' => 'name',
                        'class' => 'width200'
                    ))
                ];
                break;
            case '项目':
                $project = query('project', "coid = '" . self::$coid . "' order by time asc");
                $option = [
                    '项目' => selectMultiple(array(
                        'name' => 'targetId',
                        'field' => "concat(orderNo,name) as name,id",
                        'value' => $project['id'],
                        'table' => 'project',
                        'where' => "coid='" . self::$coid . "' order by orderNo asc",
                        'sqlId' => 'id',
                        'sqlField' => 'name',
                        'class' => 'width200'
                    ))
                ];
                break;
            default:
                $option = [];
        }
        $maxDate = accountDetailsClass::getMaxDate();
        $minDate = accountDetailsClass::getMinDate();
        $array = [
            [
                array_merge($option,[
                    "会计期间" => text(array(
                        "name" => "createTime",
                        'value' => static::rGet(self::$stid .self::$coid. 'SearchMonth') ?: date('Y-m', strtotime($maxDate)) . ' ~ ' . date('Y-m', strtotime($maxDate)),
                        'laydate' => ['type' => 'month', 'range' => '~', 'min' => "'{$minDate}'", 'max' => "'{$maxDate}'"]
                    )),
                    "科目"   => componentClass::subjectSelect(),
                ])
            ]
        ];
        return $this->tableShow($array,1);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('客户');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $button = $this->buttonGroup('projectDetails');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*列表-查询条件*/
    private function buttonGroup($page = 'projectDetails')
    {
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData&page=$page'><span class='spanButton'>导出</span></a>\n";
        }
        $button .= "<select class='select' style='margin-left: 8px' onchange='changeTableStyle(this)'>" . option(array('value' => static::rGet(self::page . 'tableStyle'), 'option' => accountDetailsClass::styleOption)) . "</select>";
        return $button;
    }

    /**
     * 获取样式
     * @return string
     */
    private function getStyle(): string
    {
        $style = static::rGet(self::page . 'tableStyle');
        if (empty($style)) {
            static::rSet(self::page . 'tableStyle', accountDetailsClass::styleOption[0]);
            $style = accountDetailsClass::styleOption[0];
        }
        static::rSet(self::page . 'tableStyle', $style);
        return $style;
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        static::rSet(self::$stid .self::$coid. 'SearchMonth', $this->post('createTime'));;
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('客户'),
            '数量金额式' => $this->moneyAndNumSearch('客户'),
        };
        return json_encode($json, 320);
    }

    /**
     * 修改列表样式
     * @return bool|string
     */
    public function changeTableStyle(): bool|string
    {
        $style = $this->post('style');

        if (!in_array($style, accountDetailsClass::styleOption)) {
            $json['warn'] = '请选择列表样式';
        } else {
            $json['warn'] = 2;
            static::rSet(self::page . 'tableStyle', $style);
        }
        return json_encode($json, 320);
    }

    private function js()
    {
        return <<<eof
<script>
   function changeTableStyle(e){
       let val = e.value;
       $.post(root+'control/adIndex.html?cla=projectDetails&fun=changeTableStyle',{style:val},function(res) {
            if (res.warn==2){
                location.reload();
            }else{
                msg(res.warn,'error')
            }
       },'json')
   }
</script>
<style>
.bold{font-weight: bold}
</style>
eof;
    }


    /**
     * 数量金额式
     * @param string $workFlow
     * @return string
     */
    public function moneyAndNumSearch($workFlow = ''): string
    {
        $subjectSearch     = query('subject', "id = '" . $this->post('subjectId') . "'");
        $subjectWhere      = '';
        $subjectAssitWhere = '';
        if ($this->post('subjectId')) {
            $subjectWhere      .= " and subjectId = '" . $this->post('subjectId') . "'";
            $subjectAssitWhere .= " and orderId = '" . $this->post('subjectId') . "'";
        }
        $like = array();
        //全等查询数组
        $equal = array(
            "a.coid"       => self::$coid,
            "a.isTemplate" => '否',
        );

        $and        = self::timeComparison($this->post('createTime'), 'month', field: "a.recordDate");
        $arr        = $this->post('createTime') ? explode(' ~ ', $this->post('createTime')) : [date('Y-m', strtotime(accountDetailsClass::getMinDate())), date('Y-m', strtotime(accountDetailsClass::getMaxDate()))];
        $startMonth = trim($arr[0]);
        $assitWhere = '';
        $targetName = '';
        switch ($workFlow) {
            case '客户':
                $assitWhere .= " and khid !=''";
                if ($this->post('targetId')) {
                    $assitWhere .= " and khid = '" . $this->post('targetId') . "'";
                    $target = query('kehu', "khid = '".$this->post('targetId')."'", "orderNo,companyName");
                    $targetName = $target['orderNo'].'-'.$target['companyName'];
                }
                break;
            case '供应商':
                $assitWhere .= " and supplierId !=''";
                if ($this->post('targetId')) {
                    $assitWhere .= " and supplierId = '" . $this->post('targetId') . "'";
                    $target = query('supplier', "id = '".$this->post('targetId')."'", "code,name");
                    $targetName = $target['code'].'-'.$target['name'];
                }
                break;
            case '员工':
                $assitWhere .= " and staffId !=''";
                if ($this->post('targetId')) {
                    $assitWhere .= " and staffId = '" . $this->post('targetId') . "'";
                    $target = query('staff', "stid = '".$this->post('targetId')."'", "orderNo,name");
                    $targetName = $target['orderNo'].'-'.$target['name'];
                }
                break;
            case '部门':
                $assitWhere .= " and departmentId !=''";
                if ($this->post('targetId')) {
                    $assitWhere .= " and departmentId = '" . $this->post('targetId') . "'";
                    $target = query('department', "id = '".$this->post('targetId')."'", "orderNo,name");
                    $targetName = $target['orderNo'].'-'.$target['name'];
                }
                break;
            case '存货':
                $assitWhere .= " and materialId !=''";
                if ($this->post('targetId')) {
                    $assitWhere .= " and materialId = '" . $this->post('targetId') . "'";
                    $target = query('material', "id = '".$this->post('targetId')."'", "code,name");
                    $targetName = $target['code'].'-'.$target['name'];
                }
                break;
            case '现金流':
                $assitWhere .= " and cashId !=''";
                if ($this->post('targetId')) {
                    $assitWhere .= " and cashId = '" . $this->post('targetId') . "'";
                    $target = query('cash', "id = '".$this->post('targetId')."'", "code,name");
                    $targetName = $target['code'].'-'.$target['name'];
                }
                break;
            case '项目':
                $assitWhere .= " and projectId !=''";
                if ($this->post('targetId')) {
                    $assitWhere .= " and projectId = '" . $this->post('targetId') . "'";
                    $target = query('project', "id = '".$this->post('targetId')."'", "orderNo,name");
                    $targetName = $target['orderNo'].'-'.$target['name'];
                }
                break;
        }

        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and . $assitWhere;
        $page  = $this->page(array("table" => "subject", "where" => "coid = '" . self::$coid . "' and (id in (select distinct b.subjectId from voucher as a join voucher_detail as b on a.id = b.orderId where 1=1 " . $assitWhere . $subjectWhere . voucherClass::joinWhere() . " ) or id in (select  id from subject_assist where orderId = id and initMoney !=0 $assitWhere $subjectAssitWhere))", "order" => "code asc"));

        static::rSet(self::$stid . self::page . 'where', $where);
        static::rSet(self::$stid . self::page . 'startMonth', $startMonth);
        static::rSet(self::$stid . self::page . 'sql', $page['fullSql']);

        static::rSet(self::$stid . self::page . 'subjectId', $subjectSearch['id']);
        static::rSet(self::$stid . self::page . 'workFlow', $workFlow);
        static::rSet(self::$stid . self::page . 'TargetId', $this->post('targetId'));
        self::$isFormat = true;
        $url            = root . "control/adIndex.html?cla=voucherEdit&fun=home";
        $tr             = '';
        foreach ($page['array'] as $array) {
            $all = find(array('table' => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "b.*,a.voucherNo,a.recordDate,a.voucherWordId", "where" => "b.subjectId = '$array[id]' " . $where . voucherClass::joinWhere() . " order by a.recordDate asc,a.voucherNo asc,b.list"));
            if (is_array($all['array']) && count($all['array']) == 0) {
                $targetId = $this->post('targetId');
                $result   = $this->initMoney($workFlow, $targetId, $array, $startMonth);
                $initDate = $startMonth . '-01';
                $tr       .= <<<eof
                    <tr>
                        <td>$initDate</td>
                        <td></td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>期初余额</td>
                        <td>{$result['jieNum']}</td>
                        <td>{$result['jiePrice']}</td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiNum']}</td>
                        <td>{$result['daiPrice']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$result['direction']}</td>
                        <td>{$result['balanceNum']}</td>
                        <td>{$result['balancePrice']}</td>
                        <td>{$result['balance']}</td>
                     </tr>
eof;
            }

            foreach ($all['array'] as $index => $item) {
                $voucherWord = query('voucher_word', "id = '$item[voucherWordId]'");
                //期初
                if ($index == 0 || (isset($all['array'][$index - 1]['subjectId']) && $item['subjectId'] != $all['array'][$index - 1]['subjectId'])) {
                    $targetId = match ($workFlow) {
                        '客户' => $item['khid'],
                        '供应商' => $item['supplierId'],
                        '员工' => $item['staffId'],
                        '部门' => $item['departmentId'],
                        '存货' => $item['materialId'],
                        '现金流' => $item['cashId'],
                        '项目' => $item['projectId'],
                    };
                    $result   = $this->initMoney($workFlow, $targetId, $array, date('Y-m', strtotime($item['recordDate'])));
                    $initDate = date('Y-m', strtotime($item['recordDate'])) . '-01';
                    $tr       .= <<<eof
                    <tr>
                        <td>$initDate</td>
                        <td></td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>期初余额</td>
                        <td>{$result['jieNum']}</td>
                        <td>{$result['jiePrice']}</td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiNum']}</td>
                        <td>{$result['daiPrice']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$result['direction']}</td>
                        <td>{$result['balanceNum']}</td>
                        <td>{$result['balancePrice']}</td>
                        <td>{$result['balance']}</td>
                     </tr>
eof;
                }
                //中间的内容
                $item['money'] = self::centToYuan($item['money']);

                $pinzheng = $voucherWord['id'] ? componentClass::urlTitle($voucherWord['word'] . '-' . $item['voucherNo'], $url . "&id={$item['orderId']}", '录凭证') : '';
                if ($item['direction'] == '借') {
                    $jieMoney = voucherClass::zeroToEmpty(number_format($item['money'], 2));
                    $jieNum   = voucherClass::zeroToEmpty(voucherEditClass::formatZero($item['voucherNum']));
                    $jiePrice = abs(accountDetailsClass::division($item['money'], $item['voucherNum']));
                    $daiMoney = '';
                    $daiNum   = '';
                    $daiPrice = '';
                } else {
                    $jieMoney = '';
                    $jieNum   = '';
                    $jiePrice = '';
                    $daiMoney = voucherClass::zeroToEmpty(number_format($item['money'], 2));
                    $daiNum   = voucherClass::zeroToEmpty(voucherEditClass::formatZero($item['voucherNum']));
                    $daiPrice = abs(accountDetailsClass::division($item['money'], $item['voucherNum']));
                }
                $targetId = match ($workFlow) {
                    '客户' => $item['khid'],
                    '供应商' => $item['supplierId'],
                    '员工' => $item['staffId'],
                    '部门' => $item['departmentId'],
                    '存货' => $item['materialId'],
                    '现金流' => $item['cashId'],
                    '项目' => $item['projectId'],
                };
                $result   = $this->balance($item['recordDate'], $item['subjectId'], $item['voucherNo'], $workFlow, $targetId);
                $tr       .= <<<eof
                     <tr>
                        <td>{$item['recordDate']}</td>
                        <td>$pinzheng</td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>{$item['summary']}</td>
                        <td>$jieNum</td>
                        <td>$jiePrice</td>
                        <td>$jieMoney</td>
                        <td>$daiNum</td>
                        <td>$daiPrice</td>
                        <td>$daiMoney</td>
                        <td>{$result['direction']}</td>
                        <td>{$result['balanceNum']}</td>
                        <td>{$result['balancePrice']}</td>
                        <td>{$result['balance']}</td>
                     </tr>
eof;
                //本期累计和本年累计
                if ((isset($all['array'][$index + 1]['subjectId']) && ($item['subjectId'] != $all['array'][$index + 1]['subjectId'] || date('Y-m', strtotime($all['array'][$index + 1]['recordDate'])) != date('Y-m', strtotime($item['recordDate'])))) ||
                    !isset($all['array'][$index + 1]['subjectId'])
                ) {
                    $targetId = match ($workFlow) {
                        '客户' => $item['khid'],
                        '供应商' => $item['supplierId'],
                        '员工' => $item['staffId'],
                        '部门' => $item['departmentId'],
                        '存货' => $item['materialId'],
                        '现金流' => $item['cashId'],
                        '项目' => $item['projectId'],
                    };
                    $interval = '';
                    if (isset($all['array'][$index + 1]['subjectId']) && $item['subjectId'] != $all['array'][$index + 1]['subjectId'] || !isset($all['array'][$index + 1]['subjectId'])) {
                        $interval = "<tr><td colspan='14' style='background-color: #f2f2f2'></td></tr>";
                    }
                    $day          = sprintf("%02d", date('t', strtotime($item['recordDate'])));
                    $endMonthDate = date('Y-m-' . $day, strtotime($item['recordDate']));
                    $result       = $this->monthBalance($workFlow, $targetId, date('Y-m', strtotime($item['recordDate'])), $item['subjectId']);
                    $balance      = $this->balance($item['recordDate'], $item['subjectId'], '累计', $workFlow, $targetId);
                    $totalBalance = $this->monthBalance($workFlow, $targetId, date('Y-m', strtotime($item['recordDate'])), $array['id'], 'year');
                    $tr           .= <<<eof
                     <tr class="bold">
                        <td>$endMonthDate</td>
                        <td></td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>本期合计</td>
                        <td>{$result['jieNum']}</td>
                        <td>{$result['jiePrice']}</td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiNum']}</td>
                        <td>{$result['daiPrice']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$balance['direction']}</td>
                        <td>{$balance['balanceNum']}</td>
                        <td>{$balance['balancePrice']}</td>
                        <td>{$balance['balance']}</td>
                     </tr>
                    <tr class="bold">
                        <td>$endMonthDate</td>
                        <td></td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>本年累计</td>
                        <td>{$totalBalance['jieNum']}</td>
                        <td>{$totalBalance['jiePrice']}</td>
                        <td>{$totalBalance['jieMoney']}</td>
                        <td>{$totalBalance['daiNum']}</td>
                        <td>{$totalBalance['daiPrice']}</td>
                        <td>{$totalBalance['daiMoney']}</td>
                        <td>{$balance['direction']}</td>
                        <td>{$balance['balanceNum']}</td>
                        <td>{$balance['balancePrice']}</td>
                        <td>{$balance['balance']}</td>
                     </tr>
                    $interval
eof;
                }
            }
        }

        $subjectName = $subjectSearch['id'] ? $subjectSearch['code'] . $subjectSearch['name'] : '所有';
        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',$arr));
        $html        = <<<eof
<div class="finance-subject-head">科目：{$subjectName}，{$workFlow}：{$targetName} {$monthSelector['button']}</div>
<table class="tableMany">
    <thead>
        <tr>
            <td rowspan="2" style="vertical-align: middle">日期</td>
            <td rowspan="2" style="vertical-align: middle">凭证字</td>
            <td rowspan="2" style="vertical-align: middle">科目</td>
            <td rowspan="2" style="vertical-align: middle">摘要</td>
            <td colspan="3" class="center">借方</td>
            <td colspan="3" class="center">贷方</td>
            <td rowspan="2" style="vertical-align: middle">方向</td>
            <td colspan="3" class="center">余额</td>
        </tr>
        <tr>
            <td>数量</td><td>单价</td><td>金额</td>
            <td>数量</td><td>单价</td><td>金额</td>
            <td>数量</td><td>单价</td><td>金额</td>
        </tr>
    </thead>
    <tbody>
       $tr
    </tbody>
</table>
eof;
        //返回
        return $page['hint'] .
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $html .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $this->style() .
            $this->js() .
            $page['button'] .
            clear;
    }

    /**
     * @return string
     */
    public function style(): string
    {
        return <<<eof
<style>
.tableMany thead tr:nth-of-type(2) {  
    background-color: #f2f2f2;
    color: #555;  
}
</style>
eof;
    }

    /**
     * 金额式
     */
    public function onlyMoneySearch($workFlow): string
    {
        $subjectSearch     = query('subject', "id = '" . $this->post('subjectId') . "'");
        $subjectWhere      = '';
        $subjectAssitWhere = '';
        if ($this->post('subjectId')) {
            $subjectWhere      .= " and subjectId = '" . $this->post('subjectId') . "'";
            $subjectAssitWhere .= " and orderId = '" . $this->post('subjectId') . "'";
        }
        $like = array();
        //全等查询数组
        $equal = array(
            "a.coid"       => self::$coid,
            "a.isTemplate" => '否',
        );

        $and        = self::timeComparison($this->post('createTime'), 'month', field: "a.recordDate");
        $arr        = $this->post('createTime') ? explode(' ~ ', $this->post('createTime')) : [date('Y-m', strtotime(accountDetailsClass::getMinDate())), date('Y-m', strtotime(accountDetailsClass::getMaxDate()))];
        $startMonth = trim($arr[0]);
        $assitWhere = '';
        $targetName = '';
        switch ($workFlow) {
            case '客户':
                $assitWhere .= " and khid !=''";
                $assitWhere .= " and khid = '" . $this->post('targetId') . "'";
                $target = query('kehu', "khid = '".$this->post('targetId')."'", "orderNo,companyName");
                $targetName = $target['orderNo'].'-'.$target['companyName'];
                break;
            case '供应商':
                $assitWhere .= " and supplierId !=''";
                $assitWhere .= " and supplierId = '" . $this->post('targetId') . "'";
                $target = query('supplier', "id = '".$this->post('targetId')."'", "code,name");
                $targetName = $target['code'].'-'.$target['name'];
                break;
            case '员工':
                $assitWhere .= " and staffId !=''";
                $assitWhere .= " and staffId = '" . $this->post('targetId') . "'";
                $target = query('staff', "stid = '".$this->post('targetId')."'", "orderNo,name");
                $targetName = $target['orderNo'].'-'.$target['name'];
                break;
            case '部门':
                $assitWhere .= " and departmentId !=''";
                $assitWhere .= " and departmentId = '" . $this->post('targetId') . "'";
                $target = query('department', "id = '".$this->post('targetId')."'", "orderNo,name");
                $targetName = $target['orderNo'].'-'.$target['name'];
                break;
            case '存货':
                $assitWhere .= " and materialId !=''";
                $assitWhere .= " and materialId = '" . $this->post('targetId') . "'";
                $target = query('material', "id = '".$this->post('targetId')."'", "code,name");
                $targetName = $target['code'].'-'.$target['name'];
                break;
            case '现金流':
                $assitWhere .= " and cashId !=''";
                $assitWhere .= " and cashId = '" . $this->post('targetId') . "'";
                $target = query('cash', "id = '".$this->post('targetId')."'", "code,name");
                $targetName = $target['code'].'-'.$target['name'];
                break;
            case '项目':
                $assitWhere .= " and projectId !=''";
                $assitWhere .= " and projectId = '" . $this->post('targetId') . "'";
                $target = query('project', "id = '".$this->post('targetId')."'", "orderNo,name");
                $targetName = $target['orderNo'].'-'.$target['name'];
                break;
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and . $assitWhere;
        $page  = $this->page(array("table" => "subject", "where" => "coid = '" . self::$coid . "' and (id in (select distinct b.subjectId from voucher as a join voucher_detail as b on a.id = b.orderId where 1=1 " . $assitWhere . $subjectWhere . voucherClass::joinWhere() . ") or id in (select  id from subject_assist where orderId = id and initMoney !=0 $assitWhere $subjectAssitWhere))", "order" => "code asc"));

        $url = root . "control/adIndex.html?cla=voucherEdit&fun=home";
        static::rSet(self::$stid . self::page . 'where', $where);
        static::rSet(self::$stid . self::page . 'startMonth', $startMonth);
        static::rSet(self::$stid . self::page . 'sql', $page['fullSql']);
        static::rSet(self::$stid . self::page . 'subjectId', $subjectSearch['id']);
        static::rSet(self::$stid . self::page . 'workFlow', $workFlow);
        static::rSet(self::$stid . self::page . 'TargetId', $this->post('targetId'));
        self::$isFormat = true;
        $tr             = '';
        foreach ($page['array'] as $array) {
            $all = find(array('table' => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "b.*,a.voucherNo,a.recordDate,a.voucherWordId", "where" => "b.subjectId = '$array[id]' " . $where . voucherClass::joinWhere() . " order by a.recordDate asc,a.voucherNo asc,b.list"));
            if (is_array($all['array']) && count($all['array']) == 0) {
                $targetId = $this->post('targetId');

                $result   = $this->initMoney($workFlow, $targetId, $array, $startMonth);
                $initDate = $startMonth . '-01';
                $tr       .= <<<eof
                    <tr>
                        <td>$initDate</td>
                        <td></td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>期初余额</td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$result['direction']}</td>
                        <td>{$result['balance']}</td>
                     </tr>
eof;
            }
            foreach ($all['array'] as $index => $item) {
                $voucherWord = query('voucher_word', "id = '$item[voucherWordId]'");
                //期初
                if ($index == 0 || (isset($all['array'][$index - 1]['subjectId']) && $item['subjectId'] != $all['array'][$index - 1]['subjectId'])) {
                    $targetId = match ($workFlow) {
                        '客户' => $item['khid'],
                        '供应商' => $item['supplierId'],
                        '员工' => $item['staffId'],
                        '部门' => $item['departmentId'],
                        '存货' => $item['materialId'],
                        '现金流' => $item['cashId'],
                        '项目' => $item['projectId'],
                    };
                    $result   = $this->initMoney($workFlow, $targetId, $array, date('Y-m', strtotime($item['recordDate'])));
                    $initDate = date('Y-m', strtotime($item['recordDate'])) . '-01';
                    $tr       .= <<<eof
                    <tr>
                        <td>$initDate</td>
                        <td></td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>期初余额</td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$result['direction']}</td>
                        <td>{$result['balance']}</td>
                     </tr>
eof;
                }

                //中间的内容
                $item['money'] = voucherClass::zeroToEmpty(number_format(self::centToYuan($item['money']), 2));
                $pinzheng      = $voucherWord['id'] ? componentClass::urlTitle($voucherWord['word'] . '-' . $item['voucherNo'], $url . "&id={$item['orderId']}", '录凭证') : '';
                if ($item['direction'] == '借') {
                    $jie = $item['money'];
                    $dai = '';
                } else {
                    $jie = '';
                    $dai = $item['money'];
                }
                $targetId = match ($workFlow) {
                    '客户' => $item['khid'],
                    '供应商' => $item['supplierId'],
                    '员工' => $item['staffId'],
                    '部门' => $item['departmentId'],
                    '存货' => $item['materialId'],
                    '现金流' => $item['cashId'],
                    '项目' => $item['projectId'],
                };
                $result   = $this->balance($item['recordDate'], $item['subjectId'], $item['voucherNo'], $workFlow, $targetId);
                $tr       .= <<<eof
                     <tr>
                        <td>{$item['recordDate']}</td>
                        <td>$pinzheng</td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>{$item['summary']}</td>
                        <td>$jie</td>
                        <td>$dai</td>
                        <td>{$result['direction']}</td>
                        <td>{$result['balance']}</td>
                     </tr>
eof;
                //本期累计和本年累计
                if ((isset($all['array'][$index + 1]['subjectId']) && ($item['subjectId'] != $all['array'][$index + 1]['subjectId'] || date('Y-m', strtotime($all['array'][$index + 1]['recordDate'])) != date('Y-m', strtotime($item['recordDate'])))) ||
                    !isset($all['array'][$index + 1]['subjectId'])
                ) {
                    $targetId = match ($workFlow) {
                        '客户' => $item['khid'],
                        '供应商' => $item['supplierId'],
                        '员工' => $item['staffId'],
                        '部门' => $item['departmentId'],
                        '存货' => $item['materialId'],
                        '现金流' => $item['cashId'],
                        '项目' => $item['projectId'],
                    };
                    $interval = '';
                    if (isset($all['array'][$index + 1]['subjectId']) && $item['subjectId'] != $all['array'][$index + 1]['subjectId'] || !isset($all['array'][$index + 1]['subjectId'])) {
                        $interval = "<tr><td colspan='14' style='background-color: #f2f2f2'></td></tr>";
                    }
                    $day          = sprintf("%02d", date('t', strtotime($item['recordDate'])));
                    $endMonthDate = date('Y-m-' . $day, strtotime($item['recordDate']));
                    $result       = $this->monthBalance($workFlow, $targetId, date('Y-m', strtotime($item['recordDate'])), $item['subjectId']);
                    $balance      = $this->balance($item['recordDate'], $item['subjectId'], '累计', $workFlow, $targetId);
                    $totalBalance = $this->monthBalance($workFlow, $targetId, date('Y-m', strtotime($item['recordDate'])), $array['id'], 'year');
                    $tr           .= <<<eof
                     <tr class="bold">
                        <td>$endMonthDate</td>
                        <td></td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>本期合计</td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$balance['direction']}</td>
                        <td>{$balance['balance']}</td>
                     </tr>
                    <tr class="bold">
                        <td>$endMonthDate</td>
                        <td></td>
                        <td>{$array['code']}&nbsp;{$array['name']}</td>
                        <td>本年累计</td>
                        <td>{$totalBalance['jieMoney']}</td>
                        <td>{$totalBalance['daiMoney']}</td>
                        <td>{$balance['direction']}</td>
                        <td>{$balance['balance']}</td>
                     </tr>
                    $interval
eof;
                }
            }
        }
        $subjectName = $subjectSearch['id'] ? $subjectSearch['code'] . $subjectSearch['name'] : '所有';
        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',$arr));
        $html        = <<<eof
<div class="finance-subject-head">科目：{$subjectName}，{$workFlow}：{$targetName} {$monthSelector['button']}</div>
<table class="tableMany">
    <thead>
        <tr>
            <td>日期</td>
            <td>凭证字</td>
            <td>科目</td>
            <td>摘要</td>
            <td>借方</td>
            <td>贷方</td>
            <td>方向</td>
            <td>余额</td>
        </tr>
    </thead>
    <tbody>
       $tr
    </tbody>
</table>
eof;
        //返回
        return $page['hint'] .
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $html .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $this->js() .
            $page['button'] .
            clear;
    }

    /**
     * 期初余额
     * @param $type
     * @param $targetId
     * @param $subject
     * @param $startMonth
     * @return array
     */
    public function initMoney($type, $targetId, $subject, $startMonth): array
    {
        $where = match ($type) {
            '客户' => " and khid = '$targetId'",
            '员工' => " and staffId = '$targetId'",
            '供应商' => " and supplierId = '$targetId'",
            '存货' => " and materialId = '$targetId'",
            '现金流' => " and cashId = '$targetId'",
            '部门' => " and departmentId = '$targetId'",
            '项目' => " and projectId = '$targetId'",
            default => ' and 1!=1'
        };
        //期初金额
        $initMoney = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "a.orderId = '$subject[id]' and a.coid = '" . self::$coid . "'" . $where, 'field' => "ifnull(sum(a.initMoney),0) as money"))['money'];

        $initNum = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'" . $where, 'sum' => "initNum"));
        $jieNum  = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'" . $where, 'sum' => "jieNum"));
        $daiNum  = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'" . $where, 'sum' => "daiNum"));

        $jieInit          = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and date_format(a.recordDate,'%Y-%m') < '$startMonth'" . $where . voucherClass::joinWhere()));
        $daiInit          = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and date_format(a.recordDate,'%Y-%m') < '$startMonth'" . $where . voucherClass::joinWhere()));
        $jieMoney         = self::centToYuan($jieInit['money'] + $subject['borrowMoney']);
        $daiMoney         = self::centToYuan($daiInit['money'] + $subject['loanMoney']);
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        if ($subject['direction'] == '借') {
            $jieInit['money'] += $initMoney;
            $balanceNum       = $jieInit['num'] + $initNum - $daiInit['num'];
        } else {
            $daiInit['money'] += $initMoney;
            $balanceNum       = $daiInit['num'] + $initNum - $jieInit['num'];
        }
        if ($jieInit['money'] == $daiInit['money']) {
            $direction = '平';
            $jieMoney  = 0;
            $daiMoney  = 0;
            $balance   = 0;
        } elseif ($jieInit['money'] > $daiInit['money']) {
            $direction = '借';
            $balance   = abs($jieInit['money'] - $daiInit['money']);
        } else {
            $direction = '贷';
            $balance   = abs($jieInit['money'] - $daiInit['money']);
        }
        $jieNum += $jieInit['num'];
        $daiNum += $daiInit['num'];
        $result = [
            'jieNum'       => voucherEditClass::formatZero($jieNum),
            'jiePrice'     => accountDetailsClass::division($jieInit['money'], $jieNum),
            'daiNum'       => voucherEditClass::formatZero($daiNum),
            'daiPrice'     => accountDetailsClass::division($daiInit['money'], $daiNum),
            'balanceNum'   => voucherEditClass::formatZero($balanceNum),
            'balancePrice' => abs(accountDetailsClass::division($jieInit['money'] - $daiInit['money'], $balanceNum)),
            'direction'    => $direction,
            'jieMoney'     => round($jieMoney, 2),
            'daiMoney'     => round($daiMoney, 2),
            'balance'      => round($balance, 2)
        ];
        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }


    /**
     * 本期合计
     */
    public function monthBalance($classify, $targetId, $month, $subjectId, $type = 'month'): array
    {
        $where        = match ($classify) {
            '客户' => " and khid = '$targetId'",
            '员工' => " and staffId = '$targetId'",
            '供应商' => " and supplierId = '$targetId'",
            '存货' => " and materialId = '$targetId'",
            '现金流' => " and cashId = '$targetId'",
            '部门' => " and departmentId = '$targetId'",
            '项目' => " and projectId = '$targetId'",
            default => ' and 1!=1'
        };
        $assistWhere  = '';
        $voucherWhere = '';
        if ($subjectId) {
            $assistWhere  .= " and a.orderId = '$subjectId'";
            $voucherWhere .= " and subjectId = '$subjectId'";
        }

        if ($type == 'year') {
            //期初金额
            $jieInit  = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "b.direction = '借'" . $where . $assistWhere, 'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"));
            $daiInit  = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "b.direction = '贷'" . $where . $assistWhere, 'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"));
            $jieMoney = $jieInit['money'];
            $daiMoney = $daiInit['money'];
            $jieNum   = $jieInit['num'];
            $daiNum   = $daiInit['num'];
            $year     = date('Y', strtotime($month . '-01'));
            $where    .= " and date_format(a.recordDate,'%Y') = '$year' and date_format(a.recordDate,'%Y-%m') <= '$month'";
        } else {
            $jieMoney = 0;
            $daiMoney = 0;
            $jieNum   = $daiNum = 0;
            $where    .= " and date_format(a.recordDate,'%Y-%m') = '$month'";
        }
        $jieVoucher          = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '借'" . $where . voucherClass::joinWhere()));
        $daiVoucher          = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '贷'" . $where . voucherClass::joinWhere()));
        $jieVoucher['money'] = self::centToYuan($jieVoucher['money']) + $jieMoney;
        $daiVoucher['money'] = self::centToYuan($daiVoucher['money']) + $daiMoney;
        $jieVoucher['num']   = $jieVoucher['num'] + $jieNum;
        $daiVoucher['num']   = $daiVoucher['num'] + $daiNum;


//        if ($jieVoucher['money'] == $daiVoucher['money'] && ($jieVoucher['money'] == 0)) {
//            $jieMoney = 0;
//            $daiMoney = 0;
//            $balance = 0;
//        } elseif ($jieVoucher['money'] > $daiVoucher['money']) {
//            $jieMoney =$balance= $jieVoucher['money']-$daiVoucher['money'];//
//            $daiMoney = 0;
//        } else {
//            $jieMoney =0;
//            $daiMoney =$balance= $daiVoucher['money']-$jieVoucher['money'];//
//        }
//
//        if ($jieVoucher['num'] > $daiVoucher['num']){
//            $jieNum = $jieVoucher['num'] - $daiVoucher['num'];//
//            $daiNum = 0;
//        }else{
//            $daiNum = $daiVoucher['num'] - $jieVoucher['num'];//
//            $jieNum = 0;
//        }
        $result = [
            'jiePrice' => accountDetailsClass::division($jieVoucher['money'], $jieVoucher['num']),
            'daiPrice' => accountDetailsClass::division($daiVoucher['money'], $daiVoucher['num']),
            'jieNum'   => voucherEditClass::formatZero($jieVoucher['num']),
            'daiNum'   => voucherEditClass::formatZero($daiVoucher['num']),
            'jieMoney' => round($jieVoucher['money'], 2),
            'daiMoney' => round($daiVoucher['money'], 2)
        ];
        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }

    /**
     * 计算余额
     * @param $recordDate
     * @param $subjectId
     * @param $vourcherNo
     * @param $type
     * @param $targetId
     * @return array
     */
    public function balance($recordDate, $subjectId, $vourcherNo, $type, $targetId): array
    {
        $where        = match ($type) {
            '客户' => " and khid = '$targetId'",
            '员工' => " and staffId = '$targetId'",
            '供应商' => " and supplierId = '$targetId'",
            '存货' => " and materialId = '$targetId'",
            '现金流' => " and cashId = '$targetId'",
            '部门' => " and departmentId = '$targetId'",
            '项目' => " and projectId = '$targetId'",
            default => ' and 1!=1'
        };
        $assistWhere  = '';
        $voucherWhere = '';
        if ($subjectId) {
            $assistWhere  .= " and a.orderId = '$subjectId'";
            $voucherWhere .= " and subjectId = '$subjectId'";
        }
        //期初金额
        $jieInit = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "b.direction = '借'" . $where . $assistWhere, 'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"));
        $daiInit = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "b.direction = '贷'" . $where . $assistWhere, 'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"));

        if ($vourcherNo == '累计') {
            $jieVoucher = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '借' and a.recordDate <= '$recordDate'" . $where . voucherClass::joinWhere()));
            $daiVoucher = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '贷' and a.recordDate <= '$recordDate'" . $where . voucherClass::joinWhere()));
        } else {
            $jieVoucher = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '借' and if(a.recordDate='$recordDate',a.voucherNo<='$vourcherNo',a.recordDate <= '$recordDate')" . $where . voucherClass::joinWhere()));
            $daiVoucher = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '贷' and if(a.recordDate='$recordDate',a.voucherNo<='$vourcherNo',a.recordDate <= '$recordDate') " . $where . voucherClass::joinWhere()));
        }
        $jieVoucher['money'] = self::centToYuan($jieVoucher['money']) + $jieInit['money'];
        $daiVoucher['money'] = self::centToYuan($daiVoucher['money']) + $daiInit['money'];
        $jieVoucher['num']   += $jieInit['num'];
        $daiVoucher['num']   += $daiInit['num'];
        $balanceNum          = abs($jieVoucher['num'] - $daiVoucher['num']);
        if ($jieVoucher['money'] == $daiVoucher['money']) {
            $direction = '平';
        } elseif ($jieVoucher['money'] > $daiVoucher['money']) {
            $direction = '借';
        } else {
            $direction = '贷';
        }
        $result = [
            'balanceNum'   => voucherEditClass::formatZero($balanceNum),
            'balancePrice' => abs(accountDetailsClass::division($jieVoucher['money'] - $daiVoucher['money'], $balanceNum)),
            'direction'    => $direction,
            'balance'      => round(abs($jieVoucher['money'] - $daiVoucher['money']), 2)
        ];
        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }

    /*列表页-查询条件*/
    public function supplierOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('供应商');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function supplier()
    {
        $html = $this->supplierOptions(false);
        $button = $this->buttonGroup('projectDetailsSupplier');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function supplierSearch()
    {
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('供应商'),
            '数量金额式' => $this->moneyAndNumSearch('供应商'),
        };
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function staffOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('员工');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function staff()
    {
        $html = $this->staffOptions(false);
        $button = $this->buttonGroup('projectDetailsStaff');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function staffSearch()
    {
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('员工'),
            '数量金额式' => $this->moneyAndNumSearch('员工'),
        };
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function departmentOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('部门');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function department()
    {
        $html = $this->departmentOptions(false);
        $button = $this->buttonGroup('projectDetailsDepartment');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function departmentSearch()
    {
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('部门'),
            '数量金额式' => $this->moneyAndNumSearch('部门'),
        };
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function materialOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('存货');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function material()
    {
        $html = $this->materialOptions(false);
        $button = $this->buttonGroup('projectDetailsMaterial');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function materialSearch()
    {
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('存货'),
            '数量金额式' => $this->moneyAndNumSearch('存货'),
        };
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function cashOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('现金流');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function cash()
    {
        $html = $this->cashOptions(false);
        $button = $this->buttonGroup('projectDetailsCash');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function cashSearch()
    {
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('现金流'),
            '数量金额式' => $this->moneyAndNumSearch('现金流'),
        };
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function projectOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('项目');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function project()
    {
        $html = $this->projectOptions(false);
        $button = $this->buttonGroup('projectDetailsProject');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function projectSearch()
    {
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('项目'),
            '数量金额式' => $this->moneyAndNumSearch('项目'),
        };
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power($this->post('page'), 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr             = [];
            $sql            = static::rGet(self::$stid . self::page . 'sql');
            $style          = $this->getStyle();
            $workFlow       = static::rGet(self::$stid . self::page . 'workFlow');
            $startMonth     = static::rGet(self::$stid . self::page . 'startMonth');
            $targetId       = $this->post(self::$stid . self::page . 'TargetId');
            $where          = static::rGet(self::$stid . self::page . 'where');
            self::$isFormat = true;
            if ($style == '金额式') {
                $title = array("日期", "凭证字", "科目", '摘要', '借方', '贷方', '方向', '余额');
                //获取查询结果
                $page['array'] = sqlFind($sql);
                foreach ($page['array'] as $array) {
                    $all = find(array('table' => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "b.*,a.voucherNo,a.recordDate,a.voucherWordId", "where" => "b.subjectId = '$array[id]' " . $where . voucherClass::joinWhere() . " order by a.recordDate asc,a.voucherNo asc,b.list"));
                    if (is_array($all['array']) && count($all['array']) == 0) {
                        $result   = $this->initMoney($workFlow, $targetId, $array, $startMonth);
                        $initDate = $startMonth . '-01';
                        $tr[]     = [
                            $initDate,
                            '',
                            $array['code'] . $array['name'],
                            '期初余额',
                            $result['jieMoney'],
                            $result['daiMoney'],
                            $result['direction'],
                            $result['balance'],
                        ];
                    }
                    foreach ($all['array'] as $index => $item) {
                        $voucherWord = query('voucher_word', "id = '$item[voucherWordId]'");
                        //期初
                        if ($index == 0 || (isset($all['array'][$index - 1]['subjectId']) && $item['subjectId'] != $all['array'][$index - 1]['subjectId'])) {
                            $targetId = match ($workFlow) {
                                '客户' => $item['khid'],
                                '供应商' => $item['supplierId'],
                                '员工' => $item['staffId'],
                                '部门' => $item['departmentId'],
                                '存货' => $item['materialId'],
                                '现金流' => $item['cashId'],
                                '项目' => $item['projectId'],
                            };
                            $result   = $this->initMoney($workFlow, $targetId, $array, date('Y-m', strtotime($item['recordDate'])));
                            $initDate = date('Y-m', strtotime($item['recordDate'])) . '-01';
                            $tr[]     = [
                                $initDate,
                                '',
                                $array['code'] . $array['name'],
                                '期初余额',
                                $result['jieMoney'],
                                $result['daiMoney'],
                                $result['direction'],
                                $result['balance'],
                            ];
                        }
                        //中间的内容
                        $item['money'] = voucherClass::zeroToEmpty(number_format(self::centToYuan($item['money']), 2));
                        $pinzheng      = $voucherWord['word'] . '-' . $item['voucherNo'];
                        if ($item['direction'] == '借') {
                            $jie = $item['money'];
                            $dai = '';
                        } else {
                            $jie = '';
                            $dai = $item['money'];
                        }
                        $targetId = match ($workFlow) {
                            '客户' => $item['khid'],
                            '供应商' => $item['supplierId'],
                            '员工' => $item['staffId'],
                            '部门' => $item['departmentId'],
                            '存货' => $item['materialId'],
                            '现金流' => $item['cashId'],
                            '项目' => $item['projectId'],
                        };
                        $result   = $this->balance($item['recordDate'], $item['subjectId'], $item['voucherNo'], $workFlow, $targetId);
                        $tr[]     = [
                            $item['recordDate'],
                            $pinzheng,
                            $array['code'] . $array['name'],
                            $item['summary'],
                            $jie,
                            $dai,
                            $result['direction'],
                            $result['balance'],
                        ];
                        //本期累计和本年累计
                        if ((isset($all['array'][$index + 1]['subjectId']) && ($item['subjectId'] != $all['array'][$index + 1]['subjectId'] || date('Y-m', strtotime($all['array'][$index + 1]['recordDate'])) != date('Y-m', strtotime($item['recordDate'])))) ||
                            !isset($all['array'][$index + 1]['subjectId'])
                        ) {
                            $targetId     = match ($workFlow) {
                                '客户' => $item['khid'],
                                '供应商' => $item['supplierId'],
                                '员工' => $item['staffId'],
                                '部门' => $item['departmentId'],
                                '存货' => $item['materialId'],
                                '现金流' => $item['cashId'],
                                '项目' => $item['projectId'],
                            };
                            $day          = sprintf("%02d", date('t', strtotime($item['recordDate'])));
                            $endMonthDate = date('Y-m-' . $day, strtotime($item['recordDate']));
                            $result       = $this->monthBalance($workFlow, $targetId, date('Y-m', strtotime($item['recordDate'])), $item['subjectId']);
                            $balance      = $this->balance($item['recordDate'], $item['subjectId'], '累计', $workFlow, $targetId);
                            $totalBalance = $this->monthBalance($workFlow, $targetId, date('Y-m', strtotime($item['recordDate'])), $array['id'], 'year');
                            $tr[]         = [
                                $endMonthDate,
                                '',
                                $array['code'] . $array['name'],
                                '本期合计',
                                $result['jieMoney'],
                                $result['daiMoney'],
                                $balance['direction'],
                                $balance['balance'],
                            ];
                            $tr[]         = [
                                $endMonthDate,
                                '',
                                $array['code'] . $array['name'],
                                '本年累计',
                                $totalBalance['jieMoney'],
                                $totalBalance['daiMoney'],
                                $balance['direction'],
                                $balance['balance'],
                            ];
                        }
                    }

                }
            } else {
                $title = array("日期", "凭证字", "科目", '摘要', '借方数量', '借方单价', '借方金额', '贷方数量', '贷方单价', '贷方金额', '方向', '数量', '单价', '余额');
                //获取查询结果
                $page['array'] = sqlFind($sql);
                foreach ($page['array'] as $array) {
                    $all = find(array('table' => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "b.*,a.voucherNo,a.recordDate,a.voucherWordId", "where" => "b.subjectId = '$array[id]' " . $where . voucherClass::joinWhere() . " order by a.recordDate asc,a.voucherNo asc,b.list"));
                    if (is_array($all['array']) && count($all['array']) == 0) {
                        $result   = $this->initMoney($workFlow, $targetId, $array, $startMonth);
                        $initDate = $startMonth . '-01';
                        $tr[]     = [
                            $initDate,
                            '',
                            $array['code'] . $array['name'],
                            '期初余额',
                            $result['jieNum'],
                            $result['jiePrice'],
                            $result['jieMoney'],
                            $result['daiNum'],
                            $result['daiPrice'],
                            $result['daiMoney'],
                            $result['direction'],
                            $result['balanceNum'],
                            $result['balancePrice'],
                            $result['balance'],
                        ];
                    }
                    foreach ($all['array'] as $index => $item) {
                        $voucherWord = query('voucher_word', "id = '$array[voucherWordId]'");
                        $subject     = query('subject', "id = '$array[subjectId]'");
                        //期初
                        if ($index == 0 || (isset($page['array'][$index - 1]['subjectId']) && $array['subjectId'] != $page['array'][$index - 1]['subjectId'])) {
                            $targetId = match ($workFlow) {
                                '客户' => $array['khid'],
                                '供应商' => $array['supplierId'],
                                '员工' => $array['staffId'],
                                '部门' => $array['departmentId'],
                                '存货' => $array['materialId'],
                                '现金流' => $array['cashId'],
                                '项目' => $array['projectId'],
                            };
                            $result   = $this->initMoney($workFlow, $targetId, $subject, date('Y-m', strtotime($array['recordDate'])));
                            $initDate = date('Y-m', strtotime($array['recordDate'])) . '-01';
                            $tr[]     = [
                                $initDate,
                                '',
                                $subject['code'] . $subject['name'],
                                '期初余额',
                                $result['jieNum'],
                                $result['jiePrice'],
                                $result['jieMoney'],
                                $result['daiNum'],
                                $result['daiPrice'],
                                $result['daiMoney'],
                                $result['direction'],
                                $result['balanceNum'],
                                $result['balancePrice'],
                                $result['balance'],
                            ];
                        }
                        //中间的内容
                        $item['money'] = self::centToYuan($item['money']);

                        $pinzheng = $voucherWord['word'] . '-' . $item['voucherNo'];
                        if ($item['direction'] == '借') {
                            $jieMoney = voucherClass::zeroToEmpty(number_format($item['money'], 2));
                            $jieNum   = voucherClass::zeroToEmpty(voucherEditClass::formatZero($item['voucherNum']));
                            $jiePrice = abs(accountDetailsClass::division($item['money'], $item['voucherNum']));
                            $daiMoney = '';
                            $daiNum   = '';
                            $daiPrice = '';
                        } else {
                            $jieMoney = '';
                            $jieNum   = '';
                            $jiePrice = '';
                            $daiMoney = voucherClass::zeroToEmpty(number_format($item['money'], 2));
                            $daiNum   = voucherClass::zeroToEmpty(voucherEditClass::formatZero($item['voucherNum']));
                            $daiPrice = abs(accountDetailsClass::division($item['money'], $item['voucherNum']));
                        }
                        $targetId = match ($workFlow) {
                            '客户' => $item['khid'],
                            '供应商' => $item['supplierId'],
                            '员工' => $item['staffId'],
                            '部门' => $item['departmentId'],
                            '存货' => $item['materialId'],
                            '现金流' => $item['cashId'],
                            '项目' => $item['projectId'],
                        };
                        $result   = $this->balance($item['recordDate'], $item['subjectId'], $item['voucherNo'], $workFlow, $targetId);
                        $tr[]     = [
                            $item['recordDate'],
                            $pinzheng,
                            $array['code'] . $array['name'],
                            $item['summary'],
                            $jieNum,
                            $jiePrice,
                            $jieMoney,
                            $daiNum,
                            $daiPrice,
                            $daiMoney,
                            $result['direction'],
                            $result['balanceNum'],
                            $result['balancePrice'],
                            $result['balance'],
                        ];
                        //本期累计和本年累计
                        if ((isset($all['array'][$index + 1]['subjectId']) && ($item['subjectId'] != $all['array'][$index + 1]['subjectId'] || date('Y-m', strtotime($all['array'][$index + 1]['recordDate'])) != date('Y-m', strtotime($item['recordDate'])))) ||
                            !isset($all['array'][$index + 1]['subjectId'])
                        ) {
                            $targetId     = match ($workFlow) {
                                '客户' => $item['khid'],
                                '供应商' => $item['supplierId'],
                                '员工' => $item['staffId'],
                                '部门' => $item['departmentId'],
                                '存货' => $item['materialId'],
                                '现金流' => $item['cashId'],
                                '项目' => $item['projectId'],
                            };
                            $day          = sprintf("%02d", date('t', strtotime($item['recordDate'])));
                            $endMonthDate = date('Y-m-' . $day, strtotime($item['recordDate']));
                            $result       = $this->monthBalance($workFlow, $targetId, date('Y-m', strtotime($item['recordDate'])), $item['subjectId']);
                            $balance      = $this->balance($item['recordDate'], $item['subjectId'], '累计', $workFlow, $targetId);
                            $totalBalance = $this->monthBalance($workFlow, $targetId, date('Y-m', strtotime($item['recordDate'])), $array['id'], 'year');
                            $tr[]         = [
                                $endMonthDate,
                                '',
                                $array['code'] . $array['name'],
                                '本期合计',
                                $result['jieNum'],
                                $result['jiePrice'],
                                $result['jieMoney'],
                                $result['daiNum'],
                                $result['daiPrice'],
                                $result['daiMoney'],
                                $balance['direction'],
                                $balance['balanceNum'],
                                $balance['balancePrice'],
                                $balance['balance'],
                            ];
                            $tr[]         = [
                                $endMonthDate,
                                '',
                                $array['code'] . $array['name'],
                                '本年累计',
                                $totalBalance['jieNum'],
                                $totalBalance['jiePrice'],
                                $totalBalance['jieMoney'],
                                $totalBalance['daiNum'],
                                $totalBalance['daiPrice'],
                                $totalBalance['daiMoney'],
                                $balance['direction'],
                                $balance['balanceNum'],
                                $balance['balancePrice'],
                                $balance['balance'],
                            ];
                        }
                    }

                }
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => $this->post('page'), "text" => $text]);
            $this->excelOut($title, $tr, self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}

